'''
该示例将手编代码完成以下泰勒级数求解问题：
(1)画出sin(x)
(2)求解sin(x)在0处的1，3，5阶泰勒展开式在[-2pi, 2pi]区间的图形（数值解）
其中sin(x)在0处的泰勒展开式为sin(x) = \sum_{k=0}^{+infty} {(-1)^k * x^{2k+1}} / (2k+1)!
'''

import numpy as np
import matplotlib.pyplot as plt

def fac(n):
    '''
    返回n的阶乘
    '''
    return (1 if n==0 else n*fac(n-1))

def item(n,x):
    '''
    返回泰勒级数求和的第n个一般项
    '''
    return ((-1)**n * x**(2*n + 1)) / fac(2*n + 1)

def sin_taylor(x, n):
    '''
    返回sin(x)函数在点0处的n阶泰勒展开式在x点的数值
    '''
    return (0 if n < 0 else sin_taylor(x, n-1) + item(n, x))

x = np.linspace(-2 * np.pi, 2 * np.pi, 101)  # 在[-2pi, 2pi]区间生成101个点
plt.plot(x, np.sin(x), 'r')  # 绘制sin(x)
plt.plot(x, sin_taylor(x, 1), 'b--')  # 1阶泰勒展开
plt.plot(x, sin_taylor(x, 3), 'g--')  # 3阶泰勒展开
plt.plot(x, sin_taylor(x, 5), 'y--')  # 5阶泰勒展开
plt.legend(['sin(x)','n=1','n=3', 'n=5'])
plt.show()  # 显示图形